alter function dbo.f_checktt_billexist
(
  @tid integer,
  @bid integer,
  @productid integer,
  @depotid integer,
  @batch bit,
  @calccost integer,
  @batchcode varchar(200),
  @produceddate datetime,
  @validdate datetime,
  @price decimal(18,8),
  @custom1 varchar(200),
  @custom2 varchar(200), 
  @custom3 varchar(200),
  @length decimal(18,8), 
  @width decimal(18,8), 
  @height decimal(18,8)
)
returns bit as
begin
  declare @count integer
  declare @exists bit
  declare @industrydepotinfo bit
  select @industrydepotinfo=p_paramvalue from ts_parameters where p_paramnm='industrydepotinfo'
  set @count=0

  if ((@calccost = 1) or (@calccost = 3)) and @batch=0
  begin
    SELECT @count=COUNT(tid) FROM tt_bill WHERE tid<>@tid AND productid=@productid AND depotid=@depotid and bid<0
      and ((@industrydepotinfo=0) 
          or (@industrydepotinfo=1 and isnull(custom1,'')=isnull(@custom1,'') and isnull(custom2,'')=isnull(@custom2,'') and isnull(custom3,'')=isnull(@custom3,'')
                                   and isnull(length,0)=isnull(@length,0) and isnull(width,0)=isnull(@width,0) and isnull(height,0)=isnull(@height,0)))
  end
  if (@calccost = 2) or (@batch=1)
  begin
    select @count=COUNT(tid) FROM tt_bill 
      WHERE tid<>@tid AND productid=@productid AND depotid=@depotid and bid<0 and batchcode=isnull(@batchcode,'') and price=@price
        and productdate=@produceddate and validdate=@validdate
        and ((@industrydepotinfo=0) 
          or (@industrydepotinfo=1 and isnull(custom1,'')=isnull(@custom1,'') and isnull(custom2,'')=isnull(@custom2,'') and isnull(custom3,'')=isnull(@custom3,'')
                                   and isnull(length,0)=isnull(@length,0) and isnull(width,0)=isnull(@width,0) and isnull(height,0)=isnull(@height,0)))
  end  
  if isnull(@count,0)>0
    set @exists=1
  else
    set @exists=0
  return @exists
end

